// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:io';

import 'package:flutter/material.dart';

import 'package:image_picker_plus_nic/image_picker_plus_nic.dart';
import 'package:image_picker_plus_nic/src/camera_display.dart';
import 'package:image_picker_plus_nic/src/dialog_widget.dart';
import 'package:image_picker_plus_nic/src/images_view_page.dart';
import 'package:image_picker_plus_nic/src/utilities/enum.dart';

/// 圖片挑選器
class CustomImagePicker extends StatefulWidget {
  final ImageSource source;
  final bool multiSelection; //是否多選
  final GalleryDisplaySettings? galleryDisplaySettings;
  final PickerSource pickerSource;
  final int? selectIndex;
  final Color primaryColor;
  final TextStyle textStyle;
  final void Function(DisplayMode m)? doChangeMode;

  const CustomImagePicker({
    Key? key,
    required this.source,
    required this.multiSelection,
    required this.galleryDisplaySettings,
    required this.pickerSource,
    required this.selectIndex,
    required this.primaryColor,
    required this.textStyle,
    this.doChangeMode,
  }) : super(key: key);

  @override
  CustomImagePickerState createState() => CustomImagePickerState();
}

class CustomImagePickerState extends State<CustomImagePicker>
    with TickerProviderStateMixin {
  final pageController = ValueNotifier(PageController());
  final clearVideoRecord = ValueNotifier(false);
  final redDeleteText = ValueNotifier(false);
  final selectedPage = ValueNotifier(SelectedPage.left);
  ValueNotifier<List<File>> multiSelectedImage = ValueNotifier([]);
  final multiSelectionMode = ValueNotifier(false);
  final showDeleteText = ValueNotifier(false);
  final selectedVideo = ValueNotifier(false);
  bool noGallery = true;
  ValueNotifier<File?> selectedCameraImage = ValueNotifier(null);
  late bool cropImage;
  late AppTheme appTheme;
  late UiTexts tapsNames;
  late bool showImagePreview; //顯示預覽
  late bool showImageCrop; //顯示裁切
  late int maximumSelection;
  final isImagesReady = ValueNotifier(false);
  final currentPage = ValueNotifier(0);
  final lastPage = ValueNotifier(0);

  late Color whiteColor;
  late Color blackColor;
  late GalleryDisplaySettings imagePickerDisplay;

  late bool enableCamera;
  late bool enableVideo;
  late String limitingText;

  late bool showInternalVideos;
  late bool showInternalImages;
  late SliverGridDelegateWithFixedCrossAxisCount gridDelegate;
  late bool cameraAndVideoEnabled;
  late bool cameraVideoOnlyEnabled;
  late bool showAllTabs;

  @override
  void initState() {
    _initializeVariables();
    super.initState();
  }

  _initializeVariables() {
    appTheme = AppTheme();
    imagePickerDisplay =
        widget.galleryDisplaySettings ?? const GalleryDisplaySettings();

    tapsNames = imagePickerDisplay.uiTexts;
    cropImage = imagePickerDisplay.cropImage;
    maximumSelection = imagePickerDisplay.maximumSelection;
    limitingText = "The limit is $maximumSelection photos or videos.";

    showImagePreview = imagePickerDisplay.showImagePreview;
    showImageCrop = cropImage;

    gridDelegate = imagePickerDisplay.gridDelegate;

    showInternalImages = widget.pickerSource != PickerSource.video;
    showInternalVideos = widget.pickerSource != PickerSource.image;

    noGallery = widget.source != ImageSource.camera;
    bool notGallery = widget.source != ImageSource.gallery;

    enableCamera = showInternalImages && notGallery;
    enableVideo = showInternalVideos && notGallery;
    cameraAndVideoEnabled = enableCamera && enableVideo;
    cameraVideoOnlyEnabled =
        cameraAndVideoEnabled && widget.source == ImageSource.camera;
    showAllTabs = cameraAndVideoEnabled && noGallery;
    whiteColor = appTheme.primaryColor;
    blackColor = appTheme.focusColor;
  }

  @override
  void dispose() {
    showDeleteText.dispose();
    selectedVideo.dispose();
    selectedPage.dispose();
    selectedCameraImage.dispose();
    pageController.dispose();
    clearVideoRecord.dispose();
    redDeleteText.dispose();
    multiSelectionMode.dispose();
    multiSelectedImage.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return buildGallery();
  }

  replacingDeleteWidget(bool showDeleteText) {
    this.showDeleteText.value = showDeleteText;
  }

  // 切換至相機
  void moveToCamera() {
    setState(() {
      enableCamera = true;
      noGallery = false;
    });
  }

  // 切換至檢視頁
  void moveToView() {
    //print('moveToCamera()');
    setState(() {
      enableCamera = false;
    });
  }

  moveToVideo() {
    setState(() {
      selectedPage.value = SelectedPage.right;
      selectedVideo.value = true;
    });
  }

  SafeArea buildGallery() {
    return SafeArea(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Flexible(
            child: enableCamera
                ? cameraPage(moveToView)
                : imagesViewPage(moveToCamera, widget.selectIndex),
          ),
        ],
      ),
    );
  }

  // 取消
  void onCancel(BuildContext context) {
    Navigator.of(context).maybePop(null);
  }

  ValueListenableBuilder<bool> cameraPage(void Function()? next) {
    return ValueListenableBuilder(
      valueListenable: selectedVideo,
      builder: (context, bool selectedVideoValue, child) => CustomCameraDisplay(
        appTheme: appTheme,
        selectedCameraImage: selectedCameraImage,
        tapsNames: tapsNames,
        enableCamera: enableCamera,
        enableVideo: enableVideo,
        replacingTabBar: replacingDeleteWidget,
        clearVideoRecord: clearVideoRecord,
        redDeleteText: redDeleteText,
        moveToVideoScreen: moveToVideo,
        selectedVideo: selectedVideoValue,
        next: next,
      ),
    );
  }

  void clearMultiImages() {
    setState(() {
      multiSelectedImage.value.clear();
      //multiSelectionMode.value = false;
    });
  }

  ImagesViewPage imagesViewPage(void Function()? next, int? selectIndex) {
    return ImagesViewPage(
      galleryDisplaySettings: widget.galleryDisplaySettings,
      appTheme: appTheme,
      clearMultiImages: clearMultiImages,
      gridDelegate: gridDelegate,
      multiSelectionMode: multiSelectionMode,
      blackColor: blackColor,
      showImagePreview: showImagePreview,
      showImageCrop: showImageCrop,
      multiSelectedImages: multiSelectedImage,
      whiteColor: whiteColor,
      cropImage: cropImage,
      multiSelection: widget.multiSelection,
      showInternalVideos: showInternalVideos,
      showInternalImages: showInternalImages,
      maximumSelection: maximumSelection,
      uiTexts: widget.galleryDisplaySettings?.uiTexts ?? const UiTexts(),
      next: next,
      selectIndex: selectIndex,
      doChangeMode: widget.doChangeMode,
      primaryColor: widget.primaryColor,
      textStyle: widget.textStyle,
    );
  }
}
